﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using System.Web.Security;
using Top.Api.Request;
using Top.Api.Response;
using System.Threading;
using Top.Api;
using AscentTopLibrary;
using AscentTopLibrary.Domain;

namespace AscentExplorer.Web.Areas.Top.Controllers
{
    [Authorize(Roles = "TaobaoUsers")]
    public class DashboardController : Controller
    {
        //private static string nick = string.Empty;
        //private static string sessionKey = string.Empty;

        const string serverUrl = "http://gw.api.taobao.com/router/rest";
        const string appKey = "12344956";
        const string appSecret = "3865429228e6ffd6fb132510ed91c2d7";

        public ActionResult Index()
        {
            //nick = Membership.GetUser(User.Identity.Name).Comment.Split(':')[1];
            //sessionKey = Membership.GetUser(User.Identity.Name).Comment.Split(':')[2];
            return View();
        }

        public void SyncItem()
        {
            using (BackgroundWorker syncItemWorker = new BackgroundWorker())
            {
                syncItemWorker.DoWork += syncItemWorker_DoWork;                
                string nick = Membership.GetUser(User.Identity.Name).Comment.Split(':')[1];
                string sessionKey = Membership.GetUser(User.Identity.Name).Comment.Split(':')[2];
                string argument = string.Format("{0}:{1}", nick, sessionKey);
                syncItemWorker.RunWorkerAsync(argument);
            }
        }

        void syncItemWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string argument = (string)e.Argument;
            string nicks = argument.Split(':')[0];
            string sessionKey = argument.Split(':')[1];

            using (var db = new TopDbContext("TopDbContext"))
            {                
                ItemsSearchRequest itemsSearchRequest = new ItemsSearchRequest() { Nicks = nicks, Fields = "num_iid,title,nick,pic_url,cid,price,type,delist_time,post_fee,score,volume", PageNo = 1, PageSize = 200 };
                ItemsSearchResponse itemsSearchResponse = null;
                do
                {
                    try
                    {
                        itemsSearchResponse = DoExecute(itemsSearchRequest, sessionKey);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    foreach (Item i in itemsSearchResponse.ItemSearch.Items)
                    {
                        //如果是有 sessionKey 的，那么就要获取详细信息
                        if (!string.IsNullOrEmpty(sessionKey))
                        {
                            //获取详情
                            ItemGetRequest itemGetRequest = new ItemGetRequest() { NumIid = i.NumIid, Fields = "detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual" };
                            ItemGetResponse itemGetResponse = null;
                            try
                            {
                                itemGetResponse = DoExecute(itemGetRequest, sessionKey);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                continue;
                            }
                            Item item = (Item)itemGetResponse.Item;
                            if (db.Items.Find(item.NumIid) != null)
                            {

                            }
                            else
                            {
                                db.Items.Add(item);
                            }
                        }
                        else
                        {
                            if (db.Items.Find(i.NumIid) != null)
                            {

                            }
                            else
                            {
                                db.Items.Add(i);
                            }
                        }
                    }
                    db.SaveChanges();
                    itemsSearchRequest.PageNo += 1;
                    Thread.Sleep(1000);
                }
                while (itemsSearchResponse.TotalResults / itemsSearchRequest.PageSize >= (itemsSearchRequest.PageNo - 1));
            }
        }

        public void SyncTrade()
        {
            using (BackgroundWorker syncTradeWorker = new BackgroundWorker())
            {
                syncTradeWorker.DoWork += syncTradeWorker_DoWork;
                string sessionKey = Membership.GetUser(User.Identity.Name).Comment.Split(':')[2];
                string argument = string.Format("{0}", sessionKey);
                syncTradeWorker.RunWorkerAsync();
            }
        }

        void syncTradeWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string sessionKey = (string)e.Argument;
            using (var db = new TopDbContext("TopDbContext"))
            {
                TradesSoldGetRequest tradesSoldGetRequest = new TradesSoldGetRequest() { Fields = "seller_nick, buyer_nick, title, type, created, tid, seller_rate, buyer_rate, status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee, received_payment, commission_fee, pic_path, num_iid, num, price, cod_fee, cod_status, shipping_type, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone , orders", PageNo = 1, PageSize = 40 };
                TradesSoldGetResponse tradesSoldGetResponse = null;
                do
                {
                    try
                    {
                        tradesSoldGetResponse = DoExecute(tradesSoldGetRequest, sessionKey);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    foreach (Trade trade in tradesSoldGetResponse.Trades)
                    {
                        if (db.Trades.Find(trade.Tid) != null)
                        {

                        }
                        else
                        {
                            db.Trades.Add(trade);
                        }
                    }
                    db.SaveChanges();
                    tradesSoldGetRequest.PageNo += 1;
                    Thread.Sleep(1000);
                }
                while ((tradesSoldGetRequest.PageNo - 1) <= (tradesSoldGetResponse.TotalResults / tradesSoldGetRequest.PageSize));
            }
        }

        public void SyncCollectItem()
        {
            using (BackgroundWorker syncCollectItemWorker = new BackgroundWorker())
            {
                syncCollectItemWorker.DoWork += syncCollectItemWorker_DoWork;
                string nick = Membership.GetUser(User.Identity.Name).Comment.Split(':')[1];
                string sessionKey = Membership.GetUser(User.Identity.Name).Comment.Split(':')[2];
                string argument = string.Format("{0}:{1}", nick, sessionKey);
                syncCollectItemWorker.RunWorkerAsync();
            }
        }
        void syncCollectItemWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string argument = (string)e.Argument;
            string nick = argument.Split(':')[0];
            string sessionKey = argument.Split(':')[1];

            using (var db = new TopDbContext("TopDbContext"))
            {
                FavoriteSearchRequest FavoriteSearchRequest = new FavoriteSearchRequest() { PageNo = 1, CollectType = "SHOP", UserNick = nick};
                FavoriteSearchResponse favoriteSearchResponse = null;
                do
                {
                    try
                    {
                        favoriteSearchResponse = DoExecute(FavoriteSearchRequest, sessionKey);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    foreach (CollectItem item in favoriteSearchResponse.CollectItems)
                    {
                        using (BackgroundWorker syncItemWorker = new BackgroundWorker())
                        {
                            syncItemWorker.DoWork += syncItemWorker_DoWork;
                            argument = string.Format("{0}:{1}", item.ItemOwnerNick, string.Empty);
                            syncItemWorker.RunWorkerAsync(argument);
                        }
                    }
                    db.SaveChanges();
                    FavoriteSearchRequest.PageNo += 1;
                    Thread.Sleep(1000);
                }
                while ((FavoriteSearchRequest.PageNo - 1) <= (favoriteSearchResponse.TotalResults / 20));
            }
        }

        T DoExecute<T>(ITopRequest<T> request, string sessionKey) where T : TopResponse
        {
            //const string serverUrl = "http://gw.api.taobao.com/router/rest";
            //const string appKey = "12364217";
            //const string appSecret = "b7b301fae6fea7c8c82207cedc7f5eed";
            ITopClient client = new DefaultTopClient(serverUrl, appKey, appSecret);
            return client.Execute<T>(request, sessionKey);
        }


    }
}
